package com.kly.smartbi.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kly.smartbi.common.ErrorCode;
import com.kly.smartbi.constant.CommonConstant;
import com.kly.smartbi.exception.ThrowUtils;
import com.kly.smartbi.manager.AllKindsAIManager;
import com.kly.smartbi.mapper.ChatConversationsMapper;
import com.kly.smartbi.model.dto.chat.ChatAddMessageDto;
import com.kly.smartbi.model.dto.chat.ChatQueryMessageDto;
import com.kly.smartbi.model.entity.ChatConversations;
import com.kly.smartbi.model.entity.ChatMessages;
import com.kly.smartbi.model.enums.ChatSendTypeEnum;
import com.kly.smartbi.service.ChatConversationsService;
import com.kly.smartbi.service.ChatMessagesService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
* @author admin
* @description 针对表【chat_conversations(对话主表)】的数据库操作Service实现
* @createDate 2025-03-30 20:43:49
*/
@Service
public class ChatConversationsServiceImpl extends ServiceImpl<ChatConversationsMapper, ChatConversations>
    implements ChatConversationsService{
    
    @Resource
    private ChatMessagesService chatMessagesService;

    @Resource
    private AllKindsAIManager allKindsAIManager;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String startChat(ChatAddMessageDto chatAddMessageDto) {
        String message = chatAddMessageDto.getMessage();
        Long conversationId = chatAddMessageDto.getConversationId();
        // 校验用户参数
        ThrowUtils.throwIf(StrUtil.isBlank(message), ErrorCode.PARAMS_ERROR, "请输入问题");
        ThrowUtils.throwIf(message.length() > 1000, ErrorCode.PARAMS_ERROR, "问题过长");
        ThrowUtils.throwIf(conversationId == null, ErrorCode.PARAMS_ERROR, "请输入会话ID");
        // 获取用户会话
        ChatConversations chatConversations = this.lambdaQuery()
                .eq(ChatConversations::getId, conversationId)
                .eq(ChatConversations::getUserId, StpUtil.getLoginIdAsString())
                .one();
        // 存储消息记录
        ChatMessages chatMessages = new ChatMessages();
        chatMessages.setConversationId(chatConversations.getId());
        chatMessages.setSenderType(ChatSendTypeEnum.USER.getValue());
        chatMessages.setContent(message);
        // 保存用户消息
        boolean save1 = chatMessagesService.save(chatMessages);
        ThrowUtils.throwIf(!save1, ErrorCode.OPERATION_ERROR, "保存消息失败");
        // 调用ai返回结果
        String conversation = allKindsAIManager.commonAi(message);
        ThrowUtils.throwIf(StrUtil.isBlank(conversation), ErrorCode.OPERATION_ERROR, "获取结果失败");
        chatMessages.setContent(conversation);
        chatMessages.setSenderType(ChatSendTypeEnum.SYSTEM.getValue());
        chatMessages.setId(null);
        boolean save2 = chatMessagesService.save(chatMessages);
        ThrowUtils.throwIf(!save2, ErrorCode.OPERATION_ERROR, "保存消息失败");
        return conversation;
    }

    @Override
    public Long createChat() {
        // 存储用户信息
        ChatConversations chatConversations = new ChatConversations();
        // 获取userId
        String loginIdAsString = StpUtil.getLoginIdAsString();
        chatConversations.setUserId(loginIdAsString);
        // 生成会话
        boolean save = this.save(chatConversations);
        ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR, "创建会话失败");
        return Long.valueOf(chatConversations.getId());
    }

    @Override
    public QueryWrapper<ChatConversations> getQueryWrapper(ChatQueryMessageDto chatQueryMessageDto) {
        String id = chatQueryMessageDto.getId();
        String userId = chatQueryMessageDto.getUserId();
        Date startTime = chatQueryMessageDto.getStartTime();
        Date lastActiveTime = chatQueryMessageDto.getLastActiveTime();
        String status = chatQueryMessageDto.getStatus();
        Date createTime = chatQueryMessageDto.getCreateTime();
        Date updateTime = chatQueryMessageDto.getUpdateTime();
        int current = chatQueryMessageDto.getCurrent();
        int pageSize = chatQueryMessageDto.getPageSize();
        String sortField = chatQueryMessageDto.getSortField();
        String sortOrder = chatQueryMessageDto.getSortOrder();
        QueryWrapper<ChatConversations> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotBlank(id), "id", id)
                .eq(StrUtil.isNotBlank(userId), "userId", userId)
                .ge(startTime != null, "startTime", startTime)
                .le(lastActiveTime != null, "lastActiveTime", lastActiveTime)
                .eq(StrUtil.isNotBlank(status), "status", status)
                .ge(createTime != null, "createTime", createTime)
                .ge(updateTime != null, "updateTime", updateTime)
                .orderBy(StrUtil.isNotBlank(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);

        return queryWrapper;
    }


}




